package com.neuedu.servlet;

import com.neuedu.dao.DeptDao;
import com.neuedu.entity.Dept;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

/**
 * http://localhost:8080/web/dept?_type=list
 */
@WebServlet(urlPatterns = "/dept")
public class DeptServlet  extends HttpServlet {




    private DeptDao deptDao = new DeptDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //针对的post
        req.setCharacterEncoding("utf-8");


        //有具体的业务代码 CRUD
        String type = req.getParameter("_type");
        //查询列表
        if(Objects.isNull(type) || "list".equals(type)){
            this.queryList(req,resp);
        }
        //新增
        else if("toAdd".equals(type)){
            this.toAdd(req,resp);
        } //新增
        else if("save".equals(type)){
            this.save(req,resp);
        }

        //修改q=前查询
        else if("toEdit".equals(type)){
            this.toEdit(req,resp);
        }
        //修改
        else if("update".equals(type)){
            this.update(req,resp);
        }

        //删除
        else if("deleteById".equals(type)){
            this.deleteById(req,resp);
        }


    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //展示一个 添加的表单
        StringBuilder form = new StringBuilder();
        form.append("  <form action='/web/dept' method='post'>				");
        form.append("      <input type='hidden' name='_type' value='save'/>    ");
        form.append("      deptno:<input type='text' name='deptno'> <br>    ");
        form.append("      dname:<input type='text' name='dname'> <br>      ");
        form.append("      loc:<input type='text' name='loc'> <br>          ");
        form.append("                                                       ");
        form.append("      <input type='submit' value='新增部门' />         ");
        form.append("                                                       ");
        form.append("  </form>                                              ");

        //讲html输出到浏览器端
        out(resp,form.toString());

    }

    /**
     * 根据主键删除一条
     * @param req
     * @param resp
     */
    private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取主键
        String deptno = req.getParameter("deptno");

        //删除
        int count = deptDao.deleteById(Integer.parseInt(deptno));
        //重定向 跳转到查询List
        resp.sendRedirect(req.getContextPath()+"/dept?_type=list");
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        //设置请求编码

        String deptno = req.getParameter("deptno");
        String dname = req.getParameter("dname");
        String loc = req.getParameter("loc");

        Dept dept = new Dept(
                Integer.parseInt(deptno),
                dname,
                loc
        );

        DeptDao deptDao = new DeptDao();
        int insert = deptDao.updateById(dept);

        System.out.println("insert = " + insert);


        //重定向 list
        //获取上下文
        String contextPath = req.getContextPath();
        resp.sendRedirect(contextPath+"/dept?_type=list");
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String where  = " where deptno = ?";
        String deptno = req.getParameter("deptno");
        Dept dept = deptDao.selectOne(where, deptno);
        //展示一个 添加的表单
        StringBuilder form = new StringBuilder();
        form.append(" <h3>部门修改</h3>				");
        form.append("  <form action='/web/dept' method='post'>				");
        form.append("      <input type='hidden' name='_type' value='update'/>    ");
        form.append("      deptno:<input type='text' name='deptno' value='"+dept.getDeptno()+"'  > <br>    ");
        form.append("      dname:<input type='text' name='dname' value='"+dept.getDname()+"'  > <br>      ");
        form.append("      loc:<input type='text' name='loc' value='"+dept.getLoc()+"'  > <br>          ");
        form.append("                                                       ");
        form.append("      <input type='submit' value='修改部门' />         ");
        form.append("                                                       ");
        form.append("  </form>                                              ");

        //讲html输出到浏览器端
        out(resp,form.toString());
    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String deptno = req.getParameter("deptno");
        String dname = req.getParameter("dname");
        String loc = req.getParameter("loc");

        Dept dept = new Dept(
                Integer.parseInt(deptno),
                dname,
                loc
        );

        DeptDao deptDao = new DeptDao();
        int insert = deptDao.insert(dept);

        System.out.println("insert = " + insert);


        //重定向 list
        //获取上下文
        String contextPath = req.getContextPath();
        resp.sendRedirect(contextPath+"/dept?_type=list");
    }

    private void queryList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String where  = "  ";
        List<Dept> depts = deptDao.selectList(where);

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append("   <a href=\"http://localhost:8080/web/dept?_type=toAdd\">部门添加</a> ");
        stringBuilder.append("    <table border=\"1\" width=\"500px\"  cellpadding=\"0\" cellspacing=\"0\">");
        stringBuilder.append("    	<tr align=\"center\">                                                  ");
        stringBuilder.append("    		<td>部门id</td>                                                      ");
        stringBuilder.append("    		<td>部门名称</td>                                                      ");
        stringBuilder.append("    		<td>办公地址</td>                                                      ");
        stringBuilder.append("    		<td>操作</td>                                                      ");
        stringBuilder.append("    	</tr>                                                                  ");

        String contextPath = req.getContextPath();
        for (int i = 0; i < depts.size(); i++) {
            Dept dept = depts.get(i);
            stringBuilder.append("    	<tr align=\"center\">                                                  ");
            stringBuilder.append("    		<td>"+dept.getDeptno()+"</td>                                                         ");
            stringBuilder.append("    		<td>"+dept.getDname()+"</td>                                                         ");
            stringBuilder.append("    		<td>"+dept.getLoc()+"</td>                                                         ");
            stringBuilder.append("    		<td>               ");
            stringBuilder.append("    		  <a href='"+contextPath+"/dept?_type=toEdit&deptno="+dept.getDeptno()+"'>修改</a>   &nbsp;&nbsp;&nbsp;&nbsp;            ");
            stringBuilder.append("    		  <a href='"+contextPath+"/dept?_type=deleteById&deptno="+dept.getDeptno()+"'>删除</a>               ");
            stringBuilder.append("    	   </td>             ");
            stringBuilder.append("    	</tr>                                                                  ");
        }
        //讲html输出到浏览器端
        out(resp,stringBuilder.toString());

    }


    /**
     * 输出响应内容(html)
     * @param response
     * @param html
     */
    public void out(HttpServletResponse response ,String html) throws IOException {
        response.setContentType("text/html;charset=utf8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.write(html);
        out.flush();
        out.close();
    }


}
